#!python
# -*- coding: utf-8 -*-

import pymysql
from flask import Blueprint, request, render_template, jsonify, current_app
from .db import get_db
from .admin import login_required

goods = Blueprint("goods", __name__)


@goods.route("/list")
def item_list():
    return "item list"

@goods.route("/info/<pid>")
def item_info(pid):
    conn = get_db()
    cur = conn.cursor()
    sql = "select productname,productdesc,price,discount,instock,selled from product where productno = '%s'" % pymysql.escape_string(pid)
    current_app.logger.debug("sql: %s" % sql)
    cur.execute(sql)
    rs = cur.fetchall()
    cur.close()
    if not rs:
        return "Not found", 404
    p = {
            "name": rs[0][0],
            "desc": rs[0][1],
            "price":rs[0][2],
            "discount":rs[0][3],
            "instock":rs[0][4],
            "selled":rs[0][5]
            }
    return jsonify(p)

@goods.route("/item/<pid>", methods=["GET", "POST"])
@login_required
def item(pid):
    conn = get_db()
    cur = conn.cursor()
    msg = ""
    if request.method == "POST":
        args={}
        for k,v in request.values.items():
            k1=k
            v1=pymysql.escape_string(v)
            args[k1]=v1
        sql = u"""update product set productname='{productname}',
            productdesc='{productdesc}',
            price='{price}',
            discount='{discount}',
            instock='{instock}'
            where productno = '{pid}'
            """.format(pid = pid, **args)
        cur.execute(sql)
        conn.commit()
        msg = u"产品信息修改成功!"
    sql = "select productno,productname,productdesc,price,discount,instock,selled from product where productno = '%s'" % pymysql.escape_string(pid)
    cur.execute(sql)
    rs = cur.fetchall()
    cur.close()
    if not rs:
        return "Not found", 404
    p = rs[0]
    return render_template("product_detail.html", product = p, msg=msg)
